<?php declare(strict_types=1);


namespace App\Util;

use Illuminate\Support\Facades\DB;

class SqlWhenUtil
{
    //将数组转换成sql语句
//update stores set
//store_name=case  when id=707 then "测试商户_1" when id=708 then "阜南县外卖电子商务服务中心_1"  else store_name end ,
//store_short_name= case when id=707 then "测试商户_2"  when id=708 then "阜南县外卖电子商务服务中心_2" else store_short_name end
// where id in (707,708)
    public function caseSql(array $data, string $where = "id"): array
    {
        //首选判断data必须是二维数组
        if (count($data) === count($data, 1)) {
            throw new \Exception("数组格式不一致，无法转换");
        }

        $batchUpdated = $batchWhere = [];
        foreach ($data as $item) {
            foreach ($item as $column => $value) {
                //获取条件
                if ($column == $where) {
                    $batchWhere[] = $value;  //值传递给条件数组
                    continue;
                }
                //设置更新语句
                $batchUpdated[$column][] = " when " . $where . "='" . $item[$where] . "'" . " then '" . $value . "' ";
            }
        }
        //处理更新语句
        foreach ($batchUpdated as $column => $sqlArr) {
            $sql = DB::raw("case " . implode("", $sqlArr) . " else " . $column . " end");
            $batchUpdated[$column] = $sql;
        }
        return [$batchWhere, $batchUpdated];
    }
}